package kite.sso.controller;

import kite.sso.config.KiteSsoConfig;
import kite.sso.message.UserEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 功能描述: <br>
 * 所属包名: kite.sso.controller<br>
 * 创建人　: 白剑<br>
 * 创建时间: 06/08/2018 12:54 Friday<br>
 * 当前版本: 1.0<br>
 * 修改历史: <br>
 * 修改时间　　　　　修改人　　　　　版本变更　　　　　修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
@RestController
@RequestMapping(KiteSsoConfig.INDEX_PATH)
public class IndexController {

    @Value("${server.context-path}")
    private String contextPath;

    @RequestMapping
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView("index");
        modelAndView.getModelMap().put("contextPath", contextPath);
        modelAndView.getModelMap().put("userId", getUserEntity().getUserId());
        modelAndView.getModelMap().put("userName", getUserEntity().getUserName());
        return modelAndView;
    }

    @RequestMapping("/user/me")
    public Map<String, Object> user() {
        Map<String, Object> map = new LinkedHashMap<>();
        // oauth2规范
        map.put("name", getUserEntity().getUsername());
        map.put("authorities", getUserEntity().getAuthorities());
        // grafana依赖email字段
        map.put("email", getUserEntity().getUserEmail());
        // kite相关系统依赖
        map.put("userId", getUserEntity().getUserId());
        map.put("userName", getUserEntity().getUserName());
        return map;
    }

    private UserEntity getUserEntity() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserEntity userEntity = (UserEntity) authentication.getPrincipal();
        return userEntity;
    }
}
